// pages/main/main.js
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentData: 0,
    tabs: [
      // {
      //   tab_id: '1',
      //   tab_name: '照片'
      // },
      {
        tab_id: '2',
        tab_name: '视频'
      },
    ],
    tabindex: 0,
    list: [
      // {
      //   name: '我导航1对应的tab页'
      // },
      {
        name: '我导航2对应的tab页'
      },
    ],
    videolist: [],
    safeTop: '',
    photolist: [], // 后台拿到的照片数组
    pageNum: 1,
    plist: [], // 渲染到页面的照片数组
    hiddenScaleBox: true,
    nowImgUrl: '', // 需要放大的图片
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    // 从app.globalData中取出照片和视频列表数据
    let imgs = app.globalData.imgs
    let videos = app.globalData.videos
    that.setData({
      safeTop: app.globalData.safeTop, // 获取安全距离
      photolist: imgs,
      videolist: videos,
      pageNum: Math.ceil(imgs.length / 6)
    })

    // console.log(that.data.photolist.slice(0, 6));
    // console.log(that.data.photolist.slice(6, 12));
    // console.log(that.data.photolist.slice(12, 18));
    // console.log(that.data.photolist.slice(18, that.data.photolist.length));

    for (let i = 0; i < that.data.pageNum; i++) {
      let ilist = []
      if (i < that.data.photolist.length - 1) {
        ilist = that.data.photolist.slice(i * 6, 6 * (i + 1))
      } else {
        ilist = that.data.photolist.slice(i * 6, that.data.photolist.length)
      }
      that.data.plist.push(ilist)
      that.setData({
        plist: that.data.plist
      })
      // console.log(that.data.plist);
    }
  },
  checkCurrent: function (e) {
    const that = this;
    if (that.data.currentData === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentData: e.target.dataset.current
      })
    }
  },

  // 切换照片和视频
  switchTab(e) {
    let that = this
    // console.log(e);
    let cindex = e.detail.current
    that.setData({
      tabindex: cindex
    })
  },

  // 切换照片页码
  switchPageNum(e) {
    let that = this
    that.setData({
      tabindex: e.currentTarget.dataset.current
    })
  },

  // 回到首页
  toIndex() {
    wx.redirectTo({
      url: '/pages/host/host',
    })
  },

  // 一键下载视频
  handleDownload(e) {
    let that = this
    wx.showLoading({
      title: '下载中...',
      icon: 'loading'
    })
    for (let j = 0; j < that.data.videolist.length; j++) {
      let fileName = new Date().valueOf();
      wx.downloadFile({
        url: that.data.videolist[j],
        filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.mp4',
        success: res => {
          // console.log(res);
          let filePath = res.filePath;
          wx.saveVideoToPhotosAlbum({
            filePath,
            success: file => {
              if (j == that.data.videolist.length - 1) {
                wx.hideLoading()
                wx.showToast({
                  title: '下载成功',
                  icon: 'success',
                  duration: 2000
                })
              }
              let fileMgr = wx.getFileSystemManager();
              fileMgr.unlink({
                filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.mp4',
                success: function (r) {},
              })
            },
            fail: err => {
              wx.hideLoading()
              // console.log(err)
              if (err.errMsg === 'saveVideoToPhotosAlbum:fail auth deny') {
                wx.showModal({
                  title: '提示',
                  content: '需要您授权保存相册',
                  showCancel: false,
                  success: data => {
                    wx.openSetting({
                      success(settingdata) {
                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                          wx.showModal({
                            title: '提示',
                            content: '获取权限成功,再次点击下载即可保存',
                            showCancel: false,
                          })
                        } else {
                          wx.showModal({
                            title: '提示',
                            content: '获取权限失败，将无法保存到相册哦~',
                            showCancel: false,
                          })
                        }
                      },
                    })
                  }
                })
              }
            }
          })
        }
      })

    }
  },

  // 点击图片放大
  toScale(e) {
    let that = this
    if (!that.data.chooseflag) {
      that.setData({
        hiddenScaleBox: false,
        nowImgUrl: e.currentTarget.dataset.url
      })
    }
  },

  // 关闭放大图片层
  closeScaleBox() {
    let that = this
    that.setData({
      hiddenScaleBox: true
    })
  },

  // 点击按钮保存图片
  saveImageToPhone: function () {
    const that = this;
    // 检查授权状态
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          // 如果没有授权，则请求授权
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              that.downloadAndSaveImage();
            },
            fail() {
              wx.showModal({
                title: '授权失败',
                content: '您拒绝了保存到相册的授权，将无法正常使用该功能。',
                showCancel: false
              });
            }
          });
        } else {
          // 如果已经授权，则直接下载并保存图片
          that.downloadAndSaveImage();
        }
      }
    });
  },
  downloadAndSaveImage: function () {
    const that = this;
    // 下载图片
    wx.downloadFile({
      url: that.data.photoUrl,
      success(res) {
        if (res.statusCode === 200) {
          // 下载成功，保存图片到相册
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success() {
              wx.showToast({
                title: '保存成功'
              });
            },
            fail() {
              wx.showToast({
                title: '保存失败',
                icon: 'none'
              });
            }
          });
        }
      },
      fail() {
        wx.showToast({
          title: '图片下载失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})